<template>
	<view class="phone-login-page">
		<u-navbar :safeAreaInsetTop="true" leftIcon="" bgColor="transparent" :placeholder="true">

			<view class="navbar-right" slot="right">
				<view class="flex-no-horizontal">
					<image src="../../static/chahao.png" class="phone-image" @click="toBack"></image>
				</view>
			</view>

		</u-navbar>
		<view class="phone-login-title">
			<text>手机登录</text>
			<text>请输入您的手机号码，登录你的账号</text>
		</view>
		<view class="phone-login-number">
			<view class="phone-login-number-right">
				<u--input placeholder="请输入中国大陆手机号" clearable border="none" v-model="phone" type="number" :maxlength="11"
				placeholderStyle="color: #CDCDCE;" @change="$u.debounce(verifyMobile($event))"
				customStyle="font-size: 32rpx;"></u--input>
			</view>
		</view>
		<view class="code-input-box flex-no-horizontal m-b-20">
			<u--input type="number" placeholder="请输入验证码" v-model="code" border="none" maxlength="4"
			placeholderStyle="color: #CDCDCE;font-size: 32rpx" customStyle="font-size: 32rpx;"/>
			<view class="get-code">
				<u-code :seconds="seconds" @end="end" @start="start" ref="uCode" @change="codeChange"></u-code>
				<button @tap="getCode" class="code-button" :class="{'code-button-hover':phone !== ''}">{{tips}}</button>
			</view>
		</view>
		<uni-transition name="slide-top" :show="isShowInvited">
			<view class="phone-login-number">
				<view class="phone-login-number-right">
					<u--input placeholder="请输入邀请码(选填)" clearable border="none" v-model="invitedCode" :maxlength="6"
					placeholderStyle="color: #CDCDCE;font-size: 32rpx" customStyle="font-size: 32rpx;"></u--input>
				</view>
			</view>
		</uni-transition>
		<view class="login-button">
			<u-button :text="logoText" shape="circle" class="button-yes" :class="{'button-yes-hover':phone !== '' && code !== ''}" @click="loginRegister"></u-button>
			<view class="f-xs text-center">未注册手机号将自动注册账号</view>
		</view>

		<view class="other-way">
			<view class="f-xs text-center m-b-20">其他登录方式</view>
			<view class="login-box-bottmom flex-no-horizontal">

				<text class="interval"></text>

				<view class="login-btn" @click="ThirdPartyLoginFun('wx')">
					<view class="login-btn-icon flex-no-horizontal">
						<u-icon name="weixin-fill" color="#FFF" size="28"></u-icon>
					</view>
				</view>

				<view class="login-btn" v-if="type !== 'Android'">
					<view class="login-btn-icon flex-no-horizontal" @click="ThirdPartyLoginFun('appleid')">
						<u-icon name="apple-fill" color="#FFF" size="28"></u-icon>
					</view>
				</view>

				<text class="interval"></text>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		userLoginApi,
		userRegisterApi,
		sendMsgApi,
		checkMobileRegisteredApi
	} from '../../api/index.js'
	import { uniAppleLogin,uniLogin,uniUserInfo } from '../../utility/weChatLogin.js'
	import {
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				tips: '',
				value: '',
				unionId: '', //微信id
				appleId:'',	//苹果id
				code: '', //验证码
				phone: '', //手机号
				invitedCode: '', // 邀请码
				seconds: 59,
				type:'',
				isShowInvited: false
			}
		},
		computed: {
			logoText() {
				return this.isShowInvited ? '登录/注册' : '登录'
			}
		},
		watch: {
			value(newValue, oldValue) {
			}
		},
		onLoad(e) {
			this.unionId = e.unionId || ''
			this.appleId = e.appleId || ''
		},
		onReady() {
			//#ifdef APP-PLUS
			this.type = plus.os.name
			//#endif
		},
		methods: {
			...mapMutations(['setUserInfo', 'setUserToken']),
			async verifyMobile(val) {
				try{
					if (val.length >= 11) {
						const res = await checkMobileRegisteredApi({mobile: val})
						console.log(res)
						this.isShowInvited = !res.data.isRegister
						if (this.isShowInvited) {
							uni.showToast({
								title: '用户未注册',
								icon: 'none'
							})
						}
					}
				}catch(err){
					console.log(err)
					//TODO handle the exception
				}
			},
			//倒计时变化
			codeChange(text) {
				this.tips = text;
			},
			//获取验证码
			async getCode() {
				try {
					if(this.phone === ''){
						uni.showToast({
							title: '请输入手机号码',
							icon: 'none'
						})
						return
					}

					if(this.phone.length < 11){
						uni.showToast({
							title: '请输入正确的手机号码',
							icon: 'none'
						})
						return
					}

					if (this.$refs.uCode.canGetCode) {
						// 模拟向后端请求验证码
						uni.showLoading({
							title: '正在获取验证码'
						})
						const res = await sendMsgApi({
							account: this.phone,
						})
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.showToast({
							title: '验证码已发送',
							icon: 'none'
						})
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					} else {
						uni.$u.toast('倒计时结束后再发送');
					}
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						title: e.message || e.data,
						icon: 'none'
					})
				}

			},
			end() {

			},
			start() {

			},

			//登录
			async loginFun(){
				try{
					uni.showLoading({
						title: '正在登录',
						mask:true
					})
					setTimeout(()=> {
						uni.hideLoading()
					}, 5000);
					//登录请求
					const loginRes = await userLoginApi({
						mobile: this.phone,
						code:this.code,
						loginType:'mobile'
					})
					//缓存用户信息
					this.setUserInfo(loginRes.data.userInfo)
					this.setUserToken('Bearer ' + loginRes.data.token)
					uni.showToast({
						title: '登录成功',
						icon: 'none',
						position: 'top'
					})
					setTimeout(() => {
						uni.reLaunch({
							url: '../ring/index'
						})
					}, 1000);

					return loginRes
				}catch(e){
					return Promise.reject(e)
				}
			},

			//登录or注册
			async loginRegister() {
				try {

					if(this.phone === ''){
						uni.showToast({
							title: '请填写手机号',
							icon: 'none',
							position: 'top'
						})
						return
					}

					if(this.phone.length < 11){
						uni.showToast({
							title: '请输入正确的手机号码',
							icon: 'none',
							position: 'top'
						})
						return
					}

					if(this.code === ''){
						uni.showToast({
							title: '请填写验证码',
							icon: 'none',
							position: 'top'
						})
						return
					}
					if(this.unionId !== '' || this.appleId !== '' || this.isShowInvited){
						//注册接口
						const res = await userRegisterApi({
							code:this.code,
							mobile: this.phone,
							unionId: this.unionId,
							appleId:this.appleId,
							invitationCode: this.invitedCode,
							registerType:this.unionId !== '' ? 'wx' : this.appleId !== '' ? 'appleid' : 'mobile',
							plate:plus.os.name === 'Android' ? 'Android' : this.unionId !== '' ? 'MacWx' : 'MacAppleId'
						})
						const loginRes = await this.loginFun()
					}else{
						const loginRes = await this.loginFun()
					}
				} catch (e) {
					console.log(e)
					//TODO handle the exception
					uni.hideLoading()
					uni.showToast({
						title: e.message || e.data,
						icon: 'none',
						position: 'top'
					})
					switch (e.code) {
						case 100701:
							//未注册
							uni.navigateTo({
								url: 'WeChatValidation?phone=' + this.phone + '&code=' + this.code
							})
							break;
						case 100702:
							//未绑定手机号

							break;
						case 100703:
							//未绑定微信号
							uni.navigateTo({
								url: 'WeChatValidation?phone=' + this.phone + '&code=' + this.code
							})
							break;
					}
				}
			},

			//第三方登录，wx - apple
			async ThirdPartyLoginFun(type){
				try{
					uni.showLoading({
						title: '正在登录',
						mask:true
					})
					setTimeout(()=> {
						uni.hideLoading()
					}, 5000);
					let data = {}
					if(type === 'wx'){
						//唤起微信登录
						const wechatRes = await uniLogin()
						//获取用户信息
						const infoRes = await uniUserInfo()
						this.unionId = infoRes.userInfo.unionId
						data = {
							unionId:infoRes.userInfo.unionId,
						}
						this.appleId = ''
					}else{
						//调起苹果登录
						const AppleRes = await uniAppleLogin()
						this.appleId = AppleRes.authResult.openid
						data = {
							appleId:AppleRes.authResult.openid,
						}
						this.unionId = ''
					}
					//登录请求
					const loginRes = await userLoginApi({
						...data,
						loginType:type
					})

					//缓存用户信息
					this.setUserInfo(loginRes.data.userInfo)
					this.setUserToken('Bearer ' + loginRes.data.token)
					uni.hideLoading()
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.switchTab({
							url: '../ring/index'
						})
					}, 1000);

				}catch(e){
					uni.hideLoading()
					uni.showToast({
						title:e.message || e.data,
						icon:'none'
					})
					switch(e.code) {
					    case 100701:
							//未注册
					        break;
					    case 100702:
					        //未绑定手机号
							uni.navigateTo({
								url:'./reg?unionId=' + this.unionId + '&appleId=' + this.appleId
							})
					        break;
					    case 100703:
					        //未绑定微信号
					        break;
					}
				}
			},

			toBack(){
				uni.navigateBack()
			},

		}
	}
</script>
<style lang="scss" scoped>
	.phone-login-page {
		height: 100vh;
		padding: 0 40rpx;
		background: url(@/static/img/login-bg.png) no-repeat;
		background-size: contain;

		.phone-image {
			width: 56rpx;
			height: 56rpx;
		}
		.phone-login-title {

			text:nth-of-type(1),
			text:nth-of-type(2) {
				display: block;
			}

			text:nth-of-type(1) {
				font-size: 56rpx;
				font-family: PingFang SC;
				font-weight: 800;
				padding-top: 131rpx;
				margin-bottom: 39rpx;
			}

			text:nth-of-type(2) {
				margin-bottom: 94rpx;
				opacity: 0.7;
			}

		}

		.phone-login-number {
			// display: flex;
			border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
			padding-bottom: 35rpx;

			.phone-login-number-left {
				display: flex;
				align-items: center;
			}

			.triangle {
				width: 0;
				height: 0;
				border-right: 10rpx solid transparent;
				border-left: 10rpx solid transparent;
				border-top: 10rpx solid #515151;
				margin: 0 30rpx 0 8rpx;
			}

			.phone-login-number-right {

			}

			::v-deep .input-placeholder {
				font-size: 32rpx;
			}
		}
		.code-input-box{
			margin-top: 20rpx;
			padding: 20rpx 0;
			justify-content: space-between;
			border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);

			.get-code{

				.code-button{
					border-radius: 10rpx;
					background-color: transparent;
					color: rgb(192, 196, 204);
					height: 68rpx;
					font-size: 26rpx;
				}
				.code-button-hover{
					border: 2rpx solid rgba(0, 0, 0,1);
					color: $uni-color-black;
				}
			}

		}

		.login-button {
			.button-yes {
				height: 98rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #FFFFFF;
				background-color: rgba(23, 23, 23, 0.15);
				// opacity: 0.15;
				margin: 101rpx 0 47rpx 0;
				font-size: 32rpx;
			}

			.button-yes-hover{
				background-color: $uni-color-black;
			}

			&>view {
				font-family: PingFang SC;
				color: rgba(0, 0, 0, 0.5);
			}
		}

		.other-way{
			position: absolute;
			left: 0;
			right: 0;
			bottom: 100px;
			&>view:first-child{
				opacity: 0.5;
			}
		}

		.login-box-bottmom{
			width: 100%;
			justify-content: space-around;
			.interval{
				width: 160rpx;
				height: 1rpx;
				background-color: #F0F0F0;
				opacity: 0;
			}

			.login-btn{
				text-align: center;
				.login-btn-title{
					margin-top: 10rpx;
					color: #7F7F7F;
					font-size: $uni-font-size-base;
				}

				.login-btn-icon{
					margin: 0 auto;
					justify-content: center;
					width: 104rpx;
					height: 104rpx;
					background-color: $uni-color-black;
					border-radius: $uni-border-radius-circle;
					image{
						width: 56rpx;
						height: 56rpx;
					}

				}
			}
		}
	}
</style>
